package com.ccb.hfms.builder.service.impl;

import java.util.List;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ccb.hfms.builder.service.IMongoCRUD;

@Service
public class MongoCRUD implements IMongoCRUD {
	
	@Autowired
    private MongoTemplate mongoTemplate;

	@Override
	public void add(JSONObject json) {
		mongoTemplate.save(json);
	}

	@Override
	public void remove(String id) {
		CriteriaDefinition criteriaDefinition = Criteria.where("id").is(id);
		Query query = new Query(criteriaDefinition);
		mongoTemplate.remove(query, JSONObject.class);
	}

	@Override
	public JSONObject findOne(String id) {
		Query query =new Query(Criteria.where("id").is(id));
    	return mongoTemplate.findOne(query, JSONObject.class);
	}

	@Override
	public void modify(String id, JSONObject json) {
		Query query =new Query(Criteria.where("id").is(id));
		Update update = new Update();
		mongoTemplate.findAndReplace(query, json);

	}

	
	@Override
	public List<JSONObject> findAll(String key, String value) {
		CriteriaDefinition criteriaDefinition = Criteria.where(key).is(value);
		Query query = new Query(criteriaDefinition);
		return mongoTemplate.find(query, JSONObject.class);
	}

	@Override
	public void remove(String key, String value) {
		CriteriaDefinition criteriaDefinition = Criteria.where(key).is(value);
		Query query = new Query(criteriaDefinition);
		mongoTemplate.remove(query, JSONObject.class);
		
	}

}
